package com.huweilong.commands;

import com.huweilong.util.DBUtil;

import java.sql.*;
import java.util.Date;
import java.util.Scanner;

/**
 * 借书操作
 *
 * @author 是阿秋啊
 * @date 2022/04/09 13:31
 **/
public class BorrowBookCommand {
    public static void main(String[] args) throws SQLException {
        // 登陆操作
        Scanner input = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String name = input.nextLine();
        int UserRid;
        try (Connection c = DBUtil.connection()) {
            // 验证用户名
            String sql = "select rid from readers where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, name);
                try (ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        System.out.println("登陆失败！");
                        return;
                    }
                    UserRid = rs.getInt("rid");
                }
            }
        }
        System.out.println("登陆成功！");
        System.out.print("请输入书名：");
        String bookName = input.nextLine();
        Integer bid = null;
        try (Connection c = DBUtil.connection()) {
            // 查找书是否存在，并且count是否足够
            String sql = "select bid, count from books where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, bookName);
                try (ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        System.out.println("没有此书！");
                        return;
                    }
                    if (rs.getInt(2) == 0) {
                        System.out.println("存量不足！");
                        return;
                    }
                    bid = rs.getInt(1);
                }
            }
        }
        // 借书操作
        try (Connection c = DBUtil.connection()) {
            String sql1 = "update books set count = count - 1 where bid = ?";
            try (PreparedStatement ps1 = c.prepareStatement(sql1)) {
                ps1.setInt(1, bid);
                ps1.executeUpdate();
            }
            String sql = "insert into records (rid,bid) values (?,?)";
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setInt(1, UserRid);
                ps.setInt(2, bid);
                // 在java上添加时间
                // ps.setTimestamp(3,new Timestamp(new Date().getTime()));
                ps.executeUpdate();
            }
        }
        System.out.println("借书成功！");
    }
}
